package
{
    import flash.errors.IOError;
    import flash.events.Event;
    import flash.events.IOErrorEvent;
    import flash.events.ProgressEvent;
    import flash.events.SecurityErrorEvent;
    import flash.external.ExternalInterface;
    import flash.net.Socket;
    import flash.utils.ByteArray;
    
    import mx.controls.Alert;

    public class SocketAppControl
    {
		private var _isConnected : Boolean ;
		private var host : String;
		private var port : int;
		private var serveraddress : String;
		private var socket : Socket=null;
		
        public function SocketAppControl(ip:String)
        {
			this.serveraddress=ip;
        }

        public function connect():void
        {
            parseSocketAddress(serveraddress);
			
			if(socket==null || !socket.connected){
				socket = new Socket(host,port);
				socket.addEventListener(Event.CONNECT,__connectHandler);
				socket.addEventListener(Event.CLOSE,__closeHandler);
				socket.addEventListener(IOErrorEvent.IO_ERROR,__ioErrorHandler);
				socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR,__securityErrorHandler);
				socket.addEventListener(ProgressEvent.SOCKET_DATA,__dataHandler);
			}
        }
        private function __connectHandler(e : Event):void
        {
            _isConnected=true;
			ExternalInterface.call("callfromAs","连接建立!");
        }
        private function __closeHandler(e : Event):void
        {
			ExternalInterface.call("callfromAs","{\"head\":{\"state_code\":\"1\",\"state_desc\":\"close\"}}");
        }
        private function __ioErrorHandler(e : IOError):void
        {
			ExternalInterface.call("callfromAs","{\"head\":{\"state_code\":\"1\",\"state_desc\":\"IOError-"+e.toString()+"!\"}}");
//			Alert.show(e.message+"~"+e.getStackTrace());
        }
        private function __securityErrorHandler(e : SecurityErrorEvent):void
        {
			ExternalInterface.call("callfromAs","{\"head\":{\"state_code\":\"1\",\"state_desc\":\"SecurityErrorEvent-"+e.toString()+"!\"}}");
//			Alert.show(e.toString());
        }
        private function __dataHandler(e : ProgressEvent):void
        {
            recevieMsg();
        }
        public function disconnect():void
        {
            socket.close();
        }
        private function parseSocketAddress(s:String):void{
            var colonIndex :int= s.indexOf(":");
            if (colonIndex > 0) {
                host = s.substring(0, colonIndex);
                port  = int(s.substring(colonIndex + 1));
            } else {
                port  = int(s.substring(colonIndex + 1));
            }
        }
        public function get isConnected():Boolean
        {
            return _isConnected;
        }
        public function sendMsg(msg : String):void
        {
//			Alert.show(socket+"~"+msg);
			var message:ByteArray = new ByteArray();  
			message.writeUTFBytes(msg+"\r\n");  
			socket.writeBytes(message);  
            socket.flush();
        }
        public function recevieMsg():void
        {
//			var packet_len:int=0;
//			try{   
////				while(true){    
//				if(packet_len == 0){   
//					if(socket.bytesAvailable < 4) return ;    
//					var temp : ByteArray = new ByteArray(); 
//					socket.readBytes(temp , 0 , 4);    
//					packet_len = int(temp.toString());    
//				}   
//				
//				if(socket.bytesAvailable < packet_len) return;    
//				var buffer : ByteArray = new ByteArray();  
//				socket.readBytes(buffer , 0 , packet_len+1);
//				ExternalInterface.call("callfromAs",buffer.toString());
//				packet_len = 0;    
//				buffer.position = 0;
////				}      
//			}catch(e : Error){   
//				ExternalInterface.call("callfromAs","{\"head\":{\"state_code\":\"1\",\"state_desc\":\"接收数据判断异常:"+e.toString()+socket.bytesAvailable+"!\"}}");
//			} 	
			var str:String = socket.readUTFBytes(socket.bytesAvailable);
			ExternalInterface.call("callfromAs",str);
//			var getMsg:ByteArray = new ByteArray;  
//			socket.readBytes(getMsg,0,socket.bytesAvailable);  
//			ExternalInterface.call("callfromAs",getMsg.toString());
        }  
     
    }
}